<template>
  <div class="Goods_params">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        <a href="/hello">首页</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        show-icon
        type="warning"
        effect="dark"
        :closable="false"
      ></el-alert>
      <!-- 及联选择框 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 商品及联选择框 -->
          <el-cascader
            v-model="selecedKeys"
            :options="goodsoPtions"
            :props="props"
            @change="handleParamsChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab切换 -->
      <el-tabs v-model="activeName" @tab-click="handleTableClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="isBtn" @click="judgeIsNum" type="primary">添加参数</el-button>
          <!-- 动态参数列表 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 每一列的参数值 -->
                <el-tag
                  @close="handleParamsClose(scope.row,index)"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                >{{item}}</el-tag>
                <!-- 新增参数 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="editParamsInfo(scope.row)"
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                >编辑</el-button>
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="judgeIsNum" :disabled="isBtn" type="primary">添加属性</el-button>
          <!-- 静态参数列表 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 每一列的参数值 -->
                <el-tag
                  @close="handleParamsClose(scope.row,index)"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                >{{item}}</el-tag>
                <!-- 新增参数 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="editParamsInfo(scope.row)"
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                >编辑</el-button>
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 动态和静态公用dialog -->
      <el-dialog
        @close="colseParamsRules"
        :title="`添加${changeTitle}`"
        :visible.sync="AdddialogVisible"
        width="50%"
      >
        <!-- <span>这是一段信息</span> -->
        <el-form
          ref="AddAttrform"
          :rules="AddAttrformRules"
          :model="AddAttrform"
          label-width="80px"
        >
          <el-form-item :label="changeTitle" prop="attr_name">
            <el-input v-model="AddAttrform.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="AdddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { getParams, ChangeParams, SetParamsInfo, SetParamsTow, RemoveParamsInfo, NewDeleteParams } from '@/api/api.js'
export default {
  name: 'BackShopParams',

  data () {
    return {
      // 被选中的值
      selecedKeys: [],
      // 层级选择框值
      goodsoPtions: [],
      // 层级选择框样式
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      // 动态参数表格
      manyTableData: [],
      // 静态参数表格
      onlyTableData: [],
      // 动态静态显示隐藏
      AdddialogVisible: false,
      // 动态/静态属性值
      AddAttrform: {
        attr_name: '',
        attr_id: ''
      },
      // 判断是否为新增还是编辑
      isNum: 0,
      // 动态/静态属性值 正则
      AddAttrformRules: {
        attr_name: [
          { required: true, message: `参数名称不能为空`, trigger: 'blur' },
        ]
      },

    };
  },

  created () {
    // 请求参数数据
    this.getParamsList()
  },
  computed: {
    // 判断选中的是否为三级id
    isBtn () {
      // 判断是否禁用btn
      if (this.selecedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 得到三级列表的id
    cateId () {
      // 如果长度为3 返回第三个值
      if (this.selecedKeys.length === 3) {
        return this.selecedKeys[2]
      }
      return null
    },
    // 计算标题
    changeTitle () {
      if (this.activeName === 'many') {
        return '动态属性'
      }
      return '静态属性'
    }
  },
  methods: {
    // 请求及联选择框的数据
    async getParamsList () {
      const { data: res } = await getParams()
      if (res.meta.status !== 200) return this.$message.error('请求参数失败')
      this.goodsoPtions = res.data
    },
    // 处理层级选择框
    handleParamsChange () {
      // 判断是否为三级
      this.getListParams();
    },
    // 切换table
    handleTableClick () {
      this.getListParams()
    },
    // 获取参数的列表数据
    async getListParams () {
      // 判断是否为三级选择框
      if (this.selecedKeys.length !== 3) {
        this.$message.info('先获得三级分类')
        this.selecedKeys = [];
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 切换 请求数据
      const { data: res } = await ChangeParams(this.cateId, { sel: this.activeName })
      if (res.meta.status !== 200) return this.$message.error('请求参数失败')
      // 分割相对应字的符串
      res.data.forEach(item => {
        // return
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 子元素新增参数
        item.inputVisible = false;
        // 新增元素的值
        item.inputValue = ''
      })
      // 判断是否是动态或静态
      if (this.activeName === 'many') {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data
      }
    },
    // 清除对应的校验 
    colseParamsRules () {
      this.$refs.AddAttrform.resetFields()
    },
    // 新增
    judgeIsNum () {
      this.isNum = 0;
      this.AdddialogVisible = true
    },
    // 编辑
    editParamsInfo (row) {
      this.isNum = 1;
      this.AdddialogVisible = true;
      this.AddAttrform.attr_id = row.attr_id
      this.AddAttrform.attr_name = row.attr_name
    },
    // 提交动态或静态
    setParams () {
      this.$refs.AddAttrform.validate(async validate => {
        if (!validate) return
        // 判断是否为添加
        if (this.isNum === 0) {
          // 三级权限的id
          const id = this.selecedKeys[this.selecedKeys.length - 1];
          //  请求添加属性的值
          const { data: res } = await SetParamsInfo(id, {
            attr_name: this.AddAttrform.attr_name,
            attr_sel: this.activeName
          });
          if (res.meta.status !== 201) return this.$message.error('请求添加参数失败')
          this.AdddialogVisible = false
          this.getListParams()
          this.$message.success('添加成功')
          return
        } else {
          // 二级权限的id
          //  请求添加属性的值
          const { data: res } = await SetParamsTow(this.cateId, this.AddAttrform.attr_id, {
            attr_name: this.AddAttrform.attr_name,
            attr_sel: this.activeName
          });
          if (res.meta.status !== 200) return this.$message.error('请求编辑参数失败')
          this.AdddialogVisible = false
          this.getListParams()
          this.$message.success('编辑参数成功')
        }
      })
    },
    // 删除参数
    async removeParams (attrId) {
      const removeReluct = await this.$messageBox('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (removeReluct !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await RemoveParamsInfo(this.cateId, attrId)
      if (res.meta.status !== 200) return this.$message.error('删除失败!');
      this.getListParams()
      this.$message.success('删除成功!')
    },
    // 回车确认新增
    // 属性新增参数离开失去焦点
    async handleInputConfirm (row) {
      row.inputVisible = false;
      // 判断传入的值是否为合法
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false;
        // 不合法直接结束后面的语句
        return
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = ''
      this.paramsFun(row)
      row.inputVisible = false;
    },
    // 添加/删除参数
    async paramsFun (row) {
      // 输入合法
      const { data: res } = await NewDeleteParams(this.cateId, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('添加参数失败')
    },
    // 点击显示新增属性框
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除参数
    handleParamsClose (row, index) {
      row.attr_vals.splice(index, 1)
      this.paramsFun(row)
    }
  },
};
</script>

<style lang="less" scoped>
.el-row {
  margin: 15px 0;
  .el-col {
    span {
      margin-right: 20px;
    }
  }
}
.el-tag {
  margin: 0px 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>